package com.cbs.android.component.network.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.cbs.android.component.log.L;
import com.cbs.android.component.network.HttpClient;
import com.cbs.android.component.network.Request;
import com.cbs.android.component.network.Response;
import com.cbs.android.component.network.ResponseHandler;
import com.cbs.android.component.network.decoder.GsonDecoder;
import com.google.gson.reflect.TypeToken;

import java.net.HttpURLConnection;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.RequestBody;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getName();
    private HttpClient httpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        httpClient = new HttpClient.Builder().followRedirects(true).build();
        httpClient.setDebug(true);
    }

    public void get(View view) {
        Request request = new Request("http://192.168.58.12:81/note/api/v1/users/1/notes")
                .setDecoder(new GsonDecoder(new TypeToken<List<Note>>() {
                }.getType()))
                .header("CBSAPPID", "1")
                .header("VERSIONID", "1")
                .header("CBSAUTHORIZATION", "aa9121320d39259f272c60da9ee975c4")
                .header("USER-ID", "1");
        httpClient.send(request);
    }

    public void post(View view) {
        RequestBody requestBody = new FormBody.Builder()
                .add("pushtoken", "中文测试+%2B")
                .add("devicetype", "0")
                .build();
        Request request = new Request("http://192.168.58.12:82/user/api/v1/users/10/pushtoken")
                .post(requestBody)
                .setResponseHandler(new ResponseHandler() {
                    @Override
                    public void onResponse(Response response) {
                        if (response.getCode() == HttpURLConnection.HTTP_CREATED) { // success
                        }
                    }

                    public void onException(Request request, Exception e) {
                    }
                });
        httpClient.send(request);
    }

    public void get302(View view) {
        Request request = new Request("http://192.168.58.103:89")
                .setResponseHandler(new ResponseHandler() {
                    @Override
                    public void onResponse(Response response) {
                        L.e(TAG, "111");
                    }

                    @Override
                    public void onException(Request request, Exception e) {
                        L.e(TAG, "222");
                    }
                });
        httpClient.send(request);
    }
}
